import tornado.web
from database import DBSession, Person

class HomeHandler(tornado.web.RequestHandler):
    def get(self):
        print 'home handler get'
        items = ["Item 1", "Item 2", "Item 3"]
        self.render("base.html", title="My title", items=items)

class UsersHandler(tornado.web.RequestHandler):
    def get(self):
        session = DBSession()
        users = session.query(Person).all()
        self.render("users.html", title="My title", users=users)

class UsersNewHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("user_new.html")

    def post(self):
        session = DBSession()
        user = Person(name=self.get_argument("username"))
        session.add(user)
        session.commit()
        self.redirect("/users/")

class UserShowHandler(tornado.web.RequestHandler):
    def get(self, username):
        session = DBSession()
        user = session.query(Person).filter(Person.name==username).one()
        self.render("user_show.html", title="My title", user=user)

class UserDeleteHandler(tornado.web.RequestHandler):
    def get(self, username):
        session = DBSession()
        user = session.query(Person).filter(Person.name==username).one()
        session.delete(user)
        session.commit()
        self.redirect("/users/")

class UserEditHandler(tornado.web.RequestHandler):
    def get(self, username):
        session = DBSession()
        user = session.query(Person).filter(Person.name==username).one()
        self.render("user_edit.html", title="My title", user=user)

    def post(self, username):
        session = DBSession()
        user = session.query(Person).filter(Person.name==username).one()
        user.name = self.get_argument("username") 
        session.add(user)
        session.commit()
         
        self.render("user_show.html", title="My title", user=user)
